﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Transactions;
using DataAccessLayer;
using BusinessLogicLayer;
using MyException;

namespace Maintain_supplier_information
{
    public partial class AddItem : System.Web.UI.Page
    {
        SupplierBizlogic sbz = new SupplierBizlogic();

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                #region Check if user exists and has permission to view this page
                if (Session["UserLoggedIn"] != null)
                {
                    List<string> list = Session["UserLoggedIn"] as List<string>;
                    if (list[0].Equals("validuser"))
                    {
                        int roleId = Convert.ToInt32(list[6]);
                        if (roleId != 5)
                        {
                            Response.Redirect("/AccessDenied.aspx");
                        }
                    }
                    else
                    {
                        Response.Redirect("/Login.aspx");
                    }
                }
                else
                {
                    Response.Redirect("/Login.aspx");
                }
                #endregion

                if (!IsPostBack)
                {
                    List<Object> category = new List<object>();
                    category = sbz.getcategories();
                    ddl_Category.DataSource = category;
                    ddl_Category.DataTextField = "CategoryName";
                    ddl_Category.DataValueField = "CategoryID";
                    ddl_Category.DataBind();

                    List<Object> suplist = new List<object>();
                    suplist = sbz.getsuppliers();
                    ddl_Supplier1.DataSource = suplist;
                    ddl_Supplier1.DataTextField = "SupplierName";
                    ddl_Supplier1.DataValueField = "SupplierID";
                    ddl_Supplier1.DataBind();
                    ddl_Supplier2.DataSource = suplist.ToList();
                    ddl_Supplier2.DataTextField = "SupplierName";
                    ddl_Supplier2.DataValueField = "SupplierID";
                    ddl_Supplier2.DataBind();
                    ddl_supplier3.DataSource = suplist.ToList();
                    ddl_supplier3.DataTextField = "SupplierName";
                    ddl_supplier3.DataValueField = "SupplierID";
                    ddl_supplier3.DataBind();

                    lblMessage.Text = "";
                }

                // Block the buttons to prevent multiple clicks by the user
                btn_Add.Attributes.Add("onclick", "this.disabled=true;" + GetPostBackEventReference(btn_Add).ToString() + ";");
            }
            catch (Exception ex)
            {
                // Release block button
                btn_Add.Enabled = true;
            }
        }

        protected void btn_Add_Click(object sender, EventArgs e)
        {
            lblMessage.Text = "";

            string itemCode = "";
            string itemName = "";
            Stationery s = new Stationery();
            Supplier sup = new Supplier();
            decimal[] price = new decimal[3];
            string[] sup_id = new string[3];
            List<SupplierDetail> supDetailList = new List<SupplierDetail>();

            try
            {
                itemCode = txt_ItemCode.Text.Trim();
                itemName = txt_ItemName.Text.Trim();
                string reorderLvl = txt_reorderlevel.Text.Trim();
                string reorderQuantity = txt_reorderqty.Text.Trim();
                string availQuantity = txt_availQty.Text.Trim();

                s.ItemCode = itemCode;
                s.CategoryID = Convert.ToInt32(ddl_Category.SelectedValue.ToString());
                s.ItemName = itemName;
                s.ReorderLevel = Convert.ToInt32(reorderLvl);
                s.ReorderQty = Convert.ToInt32(reorderQuantity);
                s.UOM = txt_UOM.Text.Trim();
                s.AvailableQty = Convert.ToInt32(availQuantity);
                s.BinNo = txt_BinNo.Text.Trim();

                if (s.ItemCode.Equals("") || itemName.Equals("") || reorderLvl.Equals("") || reorderQuantity.Equals("") || s.UOM.Equals("") || availQuantity.Equals("") || s.BinNo.Equals(""))
                {
                    throw new MissingRequiredFieldsException();
                }

                sup.SupplierID = ddl_Supplier1.SelectedValue.ToString();

                price[0] = Convert.ToDecimal(txt_price1.Text);
                price[1] = Convert.ToDecimal(txt_price2.Text);
                price[2] = Convert.ToDecimal(txt_price3.Text);

                sup_id[0] = ddl_Supplier1.SelectedValue.ToString();
                sup_id[1] = ddl_Supplier2.SelectedValue.ToString();
                sup_id[2] = ddl_supplier3.SelectedValue.ToString();

                for (int i = 1; i < 4; i++)
                {
                    SupplierDetail sd = new SupplierDetail();
                    sd.ItemCode = s.ItemCode;
                    sd.SupplierID = sup_id[i - 1];
                    sd.Price = price[i - 1];
                    sd.Rank = i;
                    supDetailList.Add(sd);
                }
                sbz.AddNewStationeryItem(s, supDetailList);
                lblMessage.Text = itemName + " has been added successfully";
                ClearFields();
            }
            catch (MissingRequiredFieldsException ex)
            {
                // Continue validation
            }
            catch (DuplicateItemCodeException ex)
            {
                btn_Add.Enabled = true;
                lblMessage.Text = "Item Code \"" + itemCode + "\" already exist";
            }
            catch (DuplicateSupplierException ex)
            {
                btn_Add.Enabled = true;
                lblMessage.Text = "Suppliers 1, 2, 3 cannot contain duplicate suppliers";
            }
            catch (SupplierPriceNotInOrderException ex)
            {
                btn_Add.Enabled = true;
                lblMessage.Text = "Suppliers should be in increasing order according to price";
            }
            catch (Exception ex)
            {
                btn_Add.Enabled = true;
            }
        }

        protected void btn_cancel_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect("/MaintainStationeryItems.aspx");
            }
            catch (Exception ex)
            {
            }
        }

        private void ClearFields()
        {
            txt_ItemCode.Text = "";
            txt_ItemName.Text = "";
            txt_reorderlevel.Text = "";
            txt_reorderqty.Text = "";
            txt_UOM.Text = "";
            txt_availQty.Text = "";
            txt_BinNo.Text = "";
            txt_price1.Text = "";
            txt_price2.Text = "";
            txt_price3.Text = "";
        }
    }
}